package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBook 地址簿
     */
    @Override
    public void add(AddressBook addressBook) {
        AddressBook address = new AddressBook();
        BeanUtils.copyProperties(addressBook, address);
        address.setUserId(BaseContext.getCurrentId());
        address.setIsDefault(0);
        addressBookMapper.add(address);
    }

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return 地址信息
     */
    @Override
    public List<AddressBook> selectByUserId() {
        return addressBookMapper.selectByUserId(BaseContext.getCurrentId());
    }

    /**
     * 根据id查询地址
     *
     * @param id 地址id
     * @return 地址信息
     */
    @Override
    public AddressBook selectById(Long id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return addressBook;
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook 地址信息
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id 地址id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    /**
     * 查询默认地址
     *
     * @return 地址信息
     */
    @Override
    public AddressBook selectDefault() {
        return addressBookMapper.selectDefault(BaseContext.getCurrentId());
    }

    /**
     * 设置默认地址
     *
     * @param addressBook 地址信息
     */
    @Override
    public void settingDefaultDddress(AddressBook addressBook) {
        // 先把所有的地址信息修改为 非默认
        List<AddressBook> addressBooks = addressBookMapper.selectByUserId(BaseContext.getCurrentId());
        addressBooks.forEach(
                address -> {
                    address.setIsDefault(0);
                    addressBookMapper.updateById(address);
                }
        );
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);
    }
}
